﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.SatinAlma.YeniYapi;
using ConfExpert.Properties;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Ithalat
{

    //TODO: stuff ile belli alanları doldur!
    //gereksiz alanları sil!

    public partial class Esleme : XForm
    {
        public Esleme()
        {
            InitializeComponent();
        }

        private void Esleme_Load(object sender, EventArgs e)
        {
            btnKaydet.Visibility = ytk(200) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;

            DataSet d = ExecuteDataSet("GetAF", cmbDonem.EditValue.ToInt());
            gridView1.Init(d.Tables[0]);
            gridView2.Init(d.Tables[1]);
            gridView1.MakeColumnInvisible("idosya");
            gridView1.YanYanaGetirSoluna("MIKTARCINSI", "FaturaNo", "FaturaTarihi", "Miktar", "BRUTKG", "FATURA_TUTARI", "DOVIZ_CINSI");
            gridView2.YanYanaGetirSoluna("TeslimSekliId", "Miktar", "GrossKg", "LineTotals", "FaturaToplami", "CurrencyId");
            gridView2.YanYanaGetir("FaturaId:InvoiceNo");
            gridView2.MakeColumnInvisible("Ay", "Sezon");

            gridView1.FormatAsNumber(1, "FATURA_TUTARI", "BRUTKG", "Miktar", "ISTATISTIKI");
            gridView2.FormatAsNumber(1, "LineTotals", "FaturaToplami", "GrossKg", "Miktar");

            gridView1.RowCellStyle += gridView1_RowCellStyle;
            gridView2.RowCellStyle += gridView1_RowCellStyle;

            gridView1.AddSummary();
            gridView2.AddSummary();

            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

            gridView1.SetViewCaption("UNSPED'den gelen ve henüz eşlenmemiş Faturalar");
            gridView2.SetViewCaption("Sistemdeki Alış Faturaları");

            gridView1.MakeReadOnly();
            gridView2.MakeReadOnly();
            gridView2.MakeRowSelectable();

            btnKaydet.ItemClick += barButtonItem1_ItemClick;
            btnRefresh.ItemClick += btnRefresh_ItemClick;
            splitContainerControl1.AutoSize();

            gridView2.OptionsView.EnableAppearanceEvenRow = gridView2.OptionsView.EnableAppearanceOddRow = false;
            //gridView1.DoubleClick += gridView1_DoubleClick;
            gridView2.RowStyle += gridView2_RowStyle;


            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Eşle", Esle);
            gm.GridMenu.AddMenu("Bırak", Birak);
            if (isKD || isAdmin)
            {
                gm.GridMenu.AddMenu("UNSPED'e Hata Bildir", hata);

                gm = GridManager.GetManager(gridView2);
                gm.GridMenu.AddMenu("Faturasını Düzenle", FaturayiDuzenle, Resources.Editor_Edit);
            }

            gridView1.Columns["REFERANS"].ColumnEdit = riHyperLink;
            gridView1.RowCellClick += gridView1_RowCellClick;

            ((RepositoryItemComboBox)cmbDonem.Edit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cmbDonem.EditValueChanged += cmbDonem_EditValueChanged;
        }

        private void hata(object sender, EventArgs e)
        {
            gridView1.EndEditing();
            DataRow r = gridView1.GetFocusedDataRow();
            if (r != null)
                if (r["REFERANS"].ToStr() == string.Empty ||
                    r["REFERANS"].ToStr().CompareTo("KRB.T6.0282") == 1)
                    using (UnspedeHataBildir uh = new UnspedeHataBildir(r["UNSPED_DOSYA_NO"].ToStr(), r["REFERANS"].ToStr()))
                        uh.ShowDialog();
                else
                    ShowErrorMessage("Bu opsiyon, 2016 ve sonrası UNSPED dosyaları içindir.");
        }

        void cmbDonem_EditValueChanged(object sender, EventArgs e)
        {
            Rfrsh();
        }

        void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            Cursor.Current = Cursors.WaitCursor;

            DataRow dr = gridView1.GetDataRow(e.RowHandle);

            switch (e.Column.FieldName)
            {
                case "REFERANS":
                    string REFERANS = dr["REFERANS"].ToStr();
                    if (REFERANS != string.Empty &&
                        dr["idosya"].ToStr() != string.Empty)
                    {
                        DataTable dtDosya = ExecuteDataTable("GetIthalatDosya", REFERANS);

                        byte[] bytes = (byte[])dtDosya.Rows[0]["Dosya"];
                        string FileName = dtDosya.Rows[0]["FileName"].ToStr();

                        DevTeam.FileManager.RunTempFile(FileName, bytes);
                    }
                    break;
            }


            Cursor.Current = Cursors.Default;
        }

        RepositoryItemHyperLinkEdit riHyperLink = new RepositoryItemHyperLinkEdit();
        DevExpress.XtraEditors.Repository.RepositoryItemTextEdit edit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();

        void gridView2_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (e.Column.FieldName == "REFERANS")
                if (gridView2.GetRowCellValue(e.RowHandle, "idosya") == DBNull.Value)
                    e.RepositoryItem = edit;
        }


        private void FaturayiDuzenle(object sender, EventArgs e)
        {
            int AlisFaturasiId = gridView2.GetFocusedRowCellValue("AlisFaturasiId").ToInt();
            if (AlisFaturasiId > 0)
                using (YeniFatura yf = new YeniFatura(1, AlisFaturasiId))
                    yf.ShowDialog();
        }

        /*
        void gridView1_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            GridHitInfo info = view.CalcHitInfo(pt);
            if (info.RowHandle > -1)
                if (view.GetFocusedDataRow() != null)
                {
                    int FaturaId = gridView1.GetFocusedDataRow()["FaturaId"].ToInt();

                    int E = gridView2.LocateByDisplayText(0, gridView2.Columns["FaturaId"], FaturaId.ToStr());
                    if (E > -1)
                        gridView2.SetRowCellValue(E, "FaturaId", null);
                    else
                        gridView2.SetFocusedRowCellValue("FaturaId", FaturaId);
                }
            //string colCaption = info.Column == null ? "N/A" : info.Column.GetCaption();
            view.EndEdit();
        }
        */

        void gridView2_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = (sender as GridView);
            if (e.RowHandle > -1)
                if (gv.GetRowCellDisplayText(e.RowHandle, "FaturaId") != string.Empty)
                    e.Appearance.BackColor = Color.SkyBlue;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
        }


        void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Rfrsh();
        }

        private void Rfrsh()
        {
            DataSet d = ExecuteDataSet("GetAF", cmbDonem.EditValue.ToInt());
            gridView1.RefreshDataSource(d.Tables[0]);
            gridView2.RefreshDataSource(d.Tables[1]);
        }

        void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView2.EndEditing();
            gridView2.Update("AlisFaturasiId,FaturaId", "AlisFaturasi");
        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
                switch (e.Column.FieldName)
                {
                    case "FaturaNo":
                    case "FaturaTarihi":
                    case "InvoiceNo":
                    case "InvoiceTarihi":

                        e.Appearance.Font = new Font(DevExpress.Utils.AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }
        }


        void Esle(object sender, EventArgs e)
        {
            int FaturaId = gridView1.GetFocusedDataRow()["FaturaId"].ToInt();
            DataRow[] dr = gridView2.DataTable().Select("FaturaId = " + FaturaId);
            if (dr.Length > 0)
                dr[0]["FaturaId"] = DBNull.Value;

            gridView2.SetFocusedRowCellValue("FaturaId", FaturaId);
        }

        void Birak(object sender, EventArgs e)
        {
            int FaturaId = gridView1.GetFocusedDataRow()["FaturaId"].ToInt();
            DataRow[] dr = gridView2.DataTable().Select("FaturaId = " + FaturaId);
            if (dr.Length > 0)
                dr[0]["FaturaId"] = DBNull.Value;
        }


    }
}
